#include "RakNetworkFactory.h"
#include "RakPeerInterface.h"
#include "MessageIdentifiers.h"
#include "BitStream.h"
#define TreeGrowthTickRate 20000 // In milliseconds. Remember this will spawn a new tree every X amount of Seconds set to a high number!!!!
#define Web "86.13.90.109"
#define Local "127.0.0.1"
#define LocalNetwork "192.168.2.5"
#include "DarkGDK.h"
#include "Player.h"
#include "World.h"
#include "gui.h"
#include "InputKeys.h"
#include "StatusBar.h"

#define  Wood 0;
char lastPacketText;
char dbTex[1000] = ""; 
int oldx = 0;
int oldy = 0;
int oldz = 0;
int newx = 0;
int newy = 0;
int newz = 0;
char message2[256] = "";
int debounce = 0;
//#include <iostream>
//#include <assert.h>
//#include <cstdio>
//#include <cstring>
//#include <stdlib.h>
//#ifdef _WIN32
//#include <conio.h>
//#endif
//#include <stdio.h>
//#include <string.h>
//#include "Timer.h"

int Inventory[2];

struct UpdateInventory
{
	unsigned char typeId;  //ID_UPDATE_INVENTORY
	unsigned int Amount; //which character is moving
	
};
    
// the main entry point for the application is this function
void EditPlayerStats(RPCParameters *rpcParameters);
void EditPlayerStats(RPCParameters *rpcParameters)
    {
	if (rpcParameters->input){
		Inventory[0] = (int)rpcParameters->input;
	}
}

void DarkGDK ( void )
{

	

	RakPeerInterface *RakPeer1 = RakNetworkFactory::GetRakPeerInterface();
	SocketDescriptor s1(0,0);  // Create the Socket Descriptor
	RakPeer1->Startup(3,0,&s1,1); // Start the Instance.
	RakPeer1->SetMaximumIncomingConnections(2);
	RakPeer1->Connect(Local,10000,0,0,0); // Hard Coded Ip.
    REGISTER_STATIC_RPC(RakPeer1, EditPlayerStats);
     
		
	
		
//	quit=true;



	// turn on sync rate and set maximum rate to 60 fps
	dbSyncOn   ( );
	dbSyncRate ( 60 );
    dbSetImageColorKey ( 255, 255, 255 );
    // Lets make an object to show we are moving for now as i cba to make terrain and such
    dbLoadImage("land.jpg",1);
	dbLoadImage("bark07.bmp",2);
    #define GRASS 15000
	dbSetImageColorKey (255, 255, 255); 
	dbLoadImage("grass.png",15000);
	dbFogOn();
    dbFogColor( 255,255,255 );
	dbFogDistance( 10000 ); 


	World LandScape( 1, 10000, 10000, 100, 100, 200 );
          LandScape.PrepareBaseTexture( 1, 2, 3 );
		  LandScape.PrepareSkyBox("hr.x",50000);
          //LandScape.TextureFillAll( 1 );
	
    int TileStatus = 0;
	    // Inventory[0] = Wood!
	//Create Our Player Object
	Player MainPlayer(0);
  //  Timer Clock();
	//GuiItem Menu(10,10,100,100);
	MainPlayer.MoveTo(5000,150,5000);
	int KeyRing[300][1];
//	int ik = 1;
//	while (ik < 300){KeyRing[ik][1] = 0;ik++;}
	int f = 0;
	int f2 = 0;
	int f3 = 0;
    int camvar = 200;
    int DigHeight = 10;
    int HouseID = 0;
    char message[1024];
	dbLoadImage("wood.png",100);
	dbLoadImage("Postracker.png",200);
	dbMakeObjectPlain(50000,100,100);
	dbRotateObject(50000,90,0,0);
	dbTextureObject(50000,200);
	//dbHideObject(50000);
	int id = 0;
	 while(  f3<= 1000 ) {
		 int XTILE = dbRND(100);
		 int ZTILE = dbRND(100);
		 int Rotation = dbRND(360);
            dbMakeObjectPlain(GRASS+id,50,20);
			dbTextureObject(GRASS+id,GRASS);
			dbPositionObject(GRASS+id,(XTILE*100)+dbRND(50),dbGetMatrixHeight(1,XTILE,ZTILE),(ZTILE*100)+dbRND(50));
			dbRotateObject(GRASS+id,0,Rotation,0);
			id++;
			f3++;
	}
	f2=0;
	
    while(  f <= 50 ) {
    while(  f2 <= 50 ) {
            dbSetMatrixHeight(1 , LandScape.GetXPlayerTile(dbCameraPositionX())+f , LandScape.GetZPlayerTile(dbCameraPositionZ())+f2,150);
			dbSetMatrixTile( 1, LandScape.GetXPlayerTile(dbCameraPositionX())+f , LandScape.GetZPlayerTile(dbCameraPositionZ())+f2, 2 );
			f2++;
	}
	f2=0;
	f++;
	}
	
	
	
	  LandScape.GenerateResourceTree( 500 , 10 );
	  LandScape.GenerateResourceIron( 500 , 100000 );
	  
	
	
	int chatTyping = 0;
	
	
	char SendString[1024];
	StatusBar WoodBar(255,0,0,500,30);

	// our main loop
	while ( LoopGDK ( ) )
	{
		WoodBar.Render(Inventory[0],100);
     int time = dbTimer();
      if ( time-KeyRing[1][1] >= TreeGrowthTickRate )
	  {
		    int Result = 0;
            Result = LandScape.ProcessTreeGrowth();
		  if ( Result != 1 )
		  {
			  LandScape.ProcessTreeGrowth(); // we havent made a tree after two failed attempt's , Lets give it a break this go or we will kill the cpu massivly!!!!!! causing a few second lockup. 
		  }
		  if ( Result == 1 ){
			  KeyRing[1][1] = dbTimer();
		  }
	  }
	

     if ( chatTyping == 1 )
	 {
       
	             strcat(SendString,  dbInput ());
				 dbSetCursor(0,580);
			     dbText(0,580,SendString);
				 debounce = 0;
				// dbSync();
	 }
	 if ( chatTyping == 2 )
	 {
		 RakPeer1->Send(SendString, (int) strlen(SendString)+1, HIGH_PRIORITY, RELIABLE_ORDERED, 0, UNASSIGNED_SYSTEM_ADDRESS, true);
		 chatTyping = 0;
		 strcpy(SendString,"");
		 debounce = 0;
	 }
	

	
         if (  dbReturnKey() == 1)
		 {
			 if(debounce != 10 )
				{
					debounce++;
				}
			 else
			 {
          	 if ( chatTyping != 1 )
			 {
				 chatTyping = 1;
				// debounce = 0;
				 

			 }
			 else 
			 {
				 //debounce = 0;
				 chatTyping = 2;
				// dbClearEntryBuffer();
				  
			 }
			 debounce = 0;
			 }
		 }

	
	    
	     if ( dbKeyState(Key_Num8) == 1)
		 {
          int dbMouse2dX = dbMouseX();
          int dbMouse2dY = dbMouseY();
		  int OldCamx = dbCameraPositionX();
		  int OldCamy = dbCameraPositionY();
		  int OldCamz = dbCameraPositionZ();
		 
		  dbPickScreen( dbMouse2dX, dbMouse2dY, 4000 );
          
		 // int XTILE = (dbGetPickVectorX()+dbCameraPositionX())/100;
		  //int ZTILE = (dbGetPickVectorZ()+dbCameraPositionZ())/100;
		  int XTILE = LandScape.GetXPlayerTile(dbCameraPositionX());
		  int ZTILE = LandScape.GetZPlayerTile(dbCameraPositionZ());

		  dbMakeObjectPlain(10000+HouseID,100,100);
		  //dbRotateObject(1000+HouseID,0,90,0);
		  dbPositionObject(10000+HouseID,XTILE*100+50,dbGetMatrixHeight(1,XTILE,ZTILE)+50,(ZTILE*100)+100);
		 // dbColorObject(1000+HouseID,dbRGB(0,0,0));
		  if ( dbImageExist(100) ){
		  dbTextureObject(10000+HouseID,100);
		  }
          dbPositionCamera(OldCamx,OldCamy,OldCamz);
		  
		 
		 HouseID++;
		 }

		  
	     if ( dbKeyState(Key_Num2) == 1)
		 {
         // int dbMouse2dX = dbMouseX();
         // int dbMouse2dY = dbMouseY();
		  int OldCamx = dbCameraPositionX();
		  int OldCamy = dbCameraPositionY();
		  int OldCamz = dbCameraPositionZ();
		 
		//  dbPickScreen( dbMouse2dX, dbMouse2dY, 4000 );
          
		 // int XTILE = (dbGetPickVectorX()+dbCameraPositionX())/100;
		  //int ZTILE = (dbGetPickVectorZ()+dbCameraPositionZ())/100;
		  int XTILE = LandScape.GetXPlayerTile(dbCameraPositionX());
		  int ZTILE = LandScape.GetZPlayerTile(dbCameraPositionZ());

		  dbMakeObjectPlain(10000+HouseID,100,100);
		  dbRotateObject(1000+HouseID,0,90,0);
		  dbPositionObject(10000+HouseID,XTILE*100+50,dbGetMatrixHeight(1,XTILE,ZTILE)+50,ZTILE*100);
		 // dbColorObject(1000+HouseID,dbRGB(0,0,0));
		  if ( dbImageExist(100) ){
		  dbTextureObject(10000+HouseID,100);
		  }
          dbPositionCamera(OldCamx,OldCamy,OldCamz);
		  
		 
		 HouseID++;
		 }
         
		   if ( dbKeyState(Key_Num6) == 1)
		 {
         // int dbMouse2dX = dbMouseX();
         // int dbMouse2dY = dbMouseY();
		  int OldCamx = dbCameraPositionX();
		  int OldCamy = dbCameraPositionY();
		  int OldCamz = dbCameraPositionZ();
		 
		//  dbPickScreen( dbMouse2dX, dbMouse2dY, 4000 );
          
		 // int XTILE = (dbGetPickVectorX()+dbCameraPositionX())/100;
		  //int ZTILE = (dbGetPickVectorZ()+dbCameraPositionZ())/100;
		  int XTILE = LandScape.GetXPlayerTile(dbCameraPositionX());
		  int ZTILE = LandScape.GetZPlayerTile(dbCameraPositionZ());

		  dbMakeObjectPlain(10000+HouseID,100,100);
		  //dbRotateObject(1000+HouseID,90,0,0);
		  dbPositionObject(10000+HouseID,XTILE*100+100,dbGetMatrixHeight(1,XTILE,ZTILE)+50,ZTILE*100+50);
		    dbRotateObject(10000+HouseID,0,90,0);
			
		 // dbColorObject(1000+HouseID,dbRGB(0,0,0));
		  if ( dbImageExist(100) ){
		  dbTextureObject(10000+HouseID,100);
		  }
          dbPositionCamera(OldCamx,OldCamy,OldCamz);
		  
		 
		 HouseID++;
		 }
		  if ( dbKeyState(Key_Num4) == 1)
		 {
         // int dbMouse2dX = dbMouseX();
         // int dbMouse2dY = dbMouseY();
		  int OldCamx = dbCameraPositionX();
		  int OldCamy = dbCameraPositionY();
		  int OldCamz = dbCameraPositionZ();
		 
		//  dbPickScreen( dbMouse2dX, dbMouse2dY, 4000 );
          
		 // int XTILE = (dbGetPickVectorX()+dbCameraPositionX())/100;
		  //int ZTILE = (dbGetPickVectorZ()+dbCameraPositionZ())/100;
		  int XTILE = LandScape.GetXPlayerTile(dbCameraPositionX());
		  int ZTILE = LandScape.GetZPlayerTile(dbCameraPositionZ());

		  dbMakeObjectPlain(10000+HouseID,100,100);
		  //dbRotateObject(1000+HouseID,90,0,0);
		  dbPositionObject(10000+HouseID,(XTILE*100),dbGetMatrixHeight(1,XTILE,ZTILE)+50,(ZTILE*100)+50);
		    dbRotateObject(10000+HouseID,0,90,0);
		 // dbColorObject(1000+HouseID,dbRGB(0,0,0));
		  if ( dbImageExist(100) ){
		  dbTextureObject(10000+HouseID,100);
		  }
          dbPositionCamera(OldCamx,OldCamy,OldCamz);
		  
		 
		 HouseID++;
		 }

		    if ( dbKeyState(Key_Num5) == 1)
		 {
         // int dbMouse2dX = dbMouseX();
         // int dbMouse2dY = dbMouseY();
		  int OldCamx = dbCameraPositionX();
		  int OldCamy = dbCameraPositionY();
		  int OldCamz = dbCameraPositionZ();
		 
		//  dbPickScreen( dbMouse2dX, dbMouse2dY, 4000 );
          
		 // int XTILE = (dbGetPickVectorX()+dbCameraPositionX())/100;
		  //int ZTILE = (dbGetPickVectorZ()+dbCameraPositionZ())/100;
		  int XTILE = LandScape.GetXPlayerTile(dbCameraPositionX());
		  int ZTILE = LandScape.GetZPlayerTile(dbCameraPositionZ());

		  dbMakeObjectPlain(10000+HouseID,100,100);
		  //dbRotateObject(1000+HouseID,90,0,0);
		  dbPositionObject(10000+HouseID,(XTILE*100)+50,dbGetMatrixHeight(1,XTILE,ZTILE)+100,(ZTILE*100)+50);
		    dbRotateObject(10000+HouseID,90,0,0);
		 // dbColorObject(1000+HouseID,dbRGB(0,0,0));
		  if ( dbImageExist(100) ){
		  dbTextureObject(10000+HouseID,100);
		  }
          dbPositionCamera(OldCamx,OldCamy,OldCamz);
		  
		 
		 HouseID++;
		 }
			   
		 if ( dbKeyState(Key_NumPlus) == 1)
		 {
			 DigHeight = DigHeight+5;
		 }
         
		 if ( dbKeyState(Key_NumMinus) == 1)
		 {
			 DigHeight = DigHeight-5;
		 }

	
		if ( dbKeyState(Key_1) == 1 )
		{
			dbSetMatrixTile( 1, LandScape.GetXPlayerTile(dbCameraPositionX()), LandScape.GetZPlayerTile(dbCameraPositionZ()), 1);
	    }
		if ( dbKeyState(Key_2) == 1 )
		{
			dbSetMatrixTile( 1, LandScape.GetXPlayerTile(dbCameraPositionX()), LandScape.GetZPlayerTile(dbCameraPositionZ()), 2 );
		}
        if ( dbKeyState(Key_3) == 1 )
		{
			dbSetMatrixTile( 1, LandScape.GetXPlayerTile(dbCameraPositionX()), LandScape.GetZPlayerTile(dbCameraPositionZ()), 3 );
		}
        if ( dbKeyState(Key_4) == 1 )
		{
			dbSetMatrixTile( 1, LandScape.GetXPlayerTile(dbCameraPositionX()), LandScape.GetZPlayerTile(dbCameraPositionZ()), 4 );
		}
		//if ( dbKeyState(Key_5) == 1 )
		//{
		//	Clock.ResetTimer();
		//}
		if ( dbKeyState(Key_B) == 1 ){
            dbSetMatrixHeight(1 , LandScape.GetXPlayerTile(dbCameraPositionX()) , LandScape.GetZPlayerTile(dbCameraPositionZ()),DigHeight);
		}
        if ( dbKeyState(Key_H) == 1 )
		{
           TileStatus = LandScape.IsResourceAtTile(LandScape.GetXPlayerTile(dbCameraPositionX()),LandScape.GetZPlayerTile(dbCameraPositionZ()));
		     if (TileStatus ==  1 ) 
			 {		
			  Inventory[0] = Inventory[0]+ LandScape.GetResourceAmountAtTile(LandScape.GetXPlayerTile(dbCameraPositionX()),LandScape.GetZPlayerTile(dbCameraPositionZ()));
			  LandScape.DeleteResource(LandScape.GetXPlayerTile(dbCameraPositionX()),LandScape.GetZPlayerTile(dbCameraPositionZ()));
			 }
			 if (TileStatus ==  2 ) 
			 {		
			  Inventory[1] = Inventory[1]+ LandScape.GetResourceAmountAtTile(LandScape.GetXPlayerTile(dbCameraPositionX()),LandScape.GetZPlayerTile(dbCameraPositionZ()));
			  LandScape.DeleteResource(LandScape.GetXPlayerTile(dbCameraPositionX()),LandScape.GetZPlayerTile(dbCameraPositionZ()));
			 }
		}


		//if ( Menu.IsMouseOver() == 1 && dbMouseClick() == 1 )
		//{
		//	Menu.MoveTo(dbMouseX(), dbMouseY());
		//}
        //	if ( Menu.Is+MouseAtResize() == 1 && dbMouseClick() == 1 )
		//{
		//	Menu.ResizeTo(dbMouseX()+5, dbMouseY()+5);
		//}
		
	
			// Player Controls 
		
	MainPlayer.Debug( Inventory[0] ,Inventory[1],Inventory[2]); // Draw Player X And Y Coords On the Screen
	//	if ( dbMouseClick() == 2 ) {
	//if ( dbKeyState(Key_Tab) != 1) {
	dbPositionObject(50000,(LandScape.GetXPlayerTile(dbCameraPositionX())*100)+50, dbGetMatrixHeight (1, LandScape.GetXPlayerTile(dbCameraPositionX()), LandScape.GetZPlayerTile(dbCameraPositionZ()))+1,(LandScape.GetZPlayerTile(dbCameraPositionZ())*100)+50);
			MainPlayer.Move(); // Move the player using Arrow Keys Note Does not Correct for Terrain Height
			if (dbKeyState(Key_F2) == 1)
			{
				if(debounce != 10 )
				{
					debounce++;
				}
				else
				{
				if ( camvar == 200 )
				{
					camvar = 80;
					debounce = 0;
					dbHideObject(50000);
				} 
				else
				{
					debounce = 0;
					camvar = 200;
					dbShowObject(50000);
				}
				}
				
			}
		
	    MainPlayer.SnapToTerrain(LandScape.GetXPlayerTile(dbCameraPositionX()),LandScape.GetZPlayerTile(dbCameraPositionZ()),camvar); // This should snap to the terrain but doesnt...
		//}	// End of Player Controls 
		dbUpdateMatrix(1);
		
	//	Menu.GuiUpdate();
	//	Clock.UpdateTimer();
// ===================================== CHAT CHAT CHAT =========================//
  

		
		Packet *packet = RakPeer1->Receive();
        
		
		if( packet ) {
		  
			if ( packet->data[0] == ID_CONNECTION_REQUEST_ACCEPTED ) 
		     {
			     strcpy ( message, "" );
				strcat ( message,"Connected To Master Server");
				
		     }
		    else if ( packet->data[0] == ID_CONNECTION_ATTEMPT_FAILED )
		     {
				strcpy ( message, "" );
				strcat ( message,"Failed To Connect"); 
             }
		    
			else if ( packet->data[0] ==  78 )
		     {
			 UpdateInventory s = *(( UpdateInventory *) packet->data);
			 Inventory[0] = s.Amount;
             }

			else if ( packet->data[0] ==  ID_CONNECTION_LOST  )
		     {
			  strcpy ( message, "" );
			  strcat ( message,"Server Shutting Down");
             }

			else 
			 { // its a chat message print it !
				strcpy ( message, "" );
				strcat ( message, (char *)packet->data );
			 }
              
			RakPeer1->DeallocatePacket(packet);
		}
	    
	dbText(0,0, message);
       
	  
// ===================================== CHAT CHAT CHAT =========================//
// Send Player Cords to server.
   
   
        oldx = newx;
		oldz = newz;
		newx = LandScape.GetXPlayerTile(dbCameraPositionX());
		newz =  LandScape.GetZPlayerTile(dbCameraPositionZ());

		if ( oldx != newx )
		{
		    strcpy(message2,"");
			char message2[1024] = "Player At IP:  X Tile Changed to: ";
			strcat(message2, RakPeer1->GetLocalIP( 0 ));
			strcat(message2, " ,");
			strcat(message2, dbStr(newx));
			
           RakPeer1->Send(message2, (int) strlen(message2)+1, HIGH_PRIORITY, RELIABLE_ORDERED, 0, UNASSIGNED_SYSTEM_ADDRESS, true);
		}

	

		if ( oldz != newz )
		{
			strcpy(message2,"");
			char message2[1024] = "Player At IP:  Z Tile Changed to: ";
			strcat(message2, RakPeer1->GetLocalIP( 0 ));
				strcat(message2, " ,");
			strcat(message2, dbStr(newz));
           RakPeer1->Send(message2, (int) strlen(message2)+1, HIGH_PRIORITY, RELIABLE_ORDERED, 0, UNASSIGNED_SYSTEM_ADDRESS, true);
		}

	dbSync ( ); // update the screen
	}

	// return back to windows
	return;
}





































































































































































































































